package com.eastdigit.system.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eastdigit.servlet.DeptPermPrepare;
import com.eastdigit.servlet.DeptPermValidate;
import com.eastdigit.servlet.ReqBean;
import com.eastdigit.servlet.RequestAttribute;
import com.eastdigit.servlet.Response;
import com.eastdigit.shiro.ShiroConstants;
import com.eastdigit.shiro.authc.IncorrectCaptchaException;
import com.eastdigit.shiro.authc.UnActiveCredentialsException;
import com.eastdigit.shiro.cache.StateTokenCache;
import com.eastdigit.system.model.BusinessException;
import com.eastdigit.system.model.IDepartment;
import com.eastdigit.system.model.IUser;
import com.eastdigit.system.service.IPermissionService;
import com.eastdigit.system.service.IUserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private StateTokenCache stateTokenCache;

    @RequestMapping(value = "/toLogin", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject toLogin() {
        return Response.responseError("3", "您已长时间没有操作，请重新登录！");
    }

    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public String toLoginGet() {
        return "/main/login";
    }

    @RequestMapping(value = "/loginInfo")
    @ResponseBody
    public JSONObject login(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();

        if (!subject.isAuthenticated()) {
            Object obj = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
            AuthenticationException authExp = (AuthenticationException) obj;
            if (authExp != null) {
                if (authExp instanceof UnknownAccountException || authExp instanceof IncorrectCredentialsException) {
                    throw new BusinessException("错误的用户账号或密码！");
                } else if (authExp instanceof IncorrectCaptchaException) {
                    throw new BusinessException("验证码输入错误！");
                } else if (authExp instanceof UnActiveCredentialsException){
                	throw new BusinessException("账号未激活！");
                } else if (authExp instanceof ExcessiveAttemptsException) {
                    throw new BusinessException("密码错误过多，请稍后再试！");
                } else {
                    throw new BusinessException("用户名或密码错误！");
                }
            } else {
                throw new BusinessException("用户名或密码错误！");
            }
        }
        String userId = (String) subject.getPrincipals().iterator().next();
        ReqBean reqBean = (ReqBean) request.getAttribute(ReqBean.NAME);
        JSONObject jsonObject = new JSONObject();
        if (reqBean.isStateless()) {
            jsonObject.put(ShiroConstants.PARAM_TOKEN, reqBean.getToken());
        } else {
            jsonObject.put("sid", subject.getSession().getId());
        }
        jsonObject
                .put("user", userService.login(userId, reqBean.getInfo("deviceType"), reqBean.getInfo("deviceToken")));
        return Response.response(jsonObject);
    }

    @RequestMapping(value = "/logout")
    @ResponseBody
    public JSONObject logout(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        SecurityUtils.getSubject().logout();
        stateTokenCache.removeToken(reqBean.getToken());
        return Response.responseSuccess();
    }

    /**
     * 用户刷新页面
     * 
     * @param reqBean
     * @return
     */
    @RequestMapping(value = "/refresh")
    @ResponseBody
    public JSONObject refresh(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) throws Exception {
        return Response.responseSuccess(userService.login(reqBean.getUserId(), "", ""));
    }

    @RequestMapping(value = "/query")
    @ResponseBody
    @DeptPermPrepare(id = "userId", deptId = "deptId")
    public JSONObject queryUser(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(userService.queryTable(reqBean));
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    @DeptPermValidate(id = "userId", deptId = "deptId")
    public JSONObject addUser(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        userService.add(userService.getUserFromRequest(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    @DeptPermValidate(id = "userId", deptId = "deptId")
    public JSONObject updateUser(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        userService.update(userService.getUserFromRequest(reqBean));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    @DeptPermValidate(id = "userId", deptId = "deptId")
    public JSONObject removeUser(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        userService.delete(reqBean.getInfo("userId"));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/updatePassword")
    @ResponseBody
    public JSONObject updatePassword(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        userService.updatePassword(reqBean.getInfo("userId"), reqBean.getInfo("password"),
                reqBean.getInfo("newPassword"));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/resetPassword")
    @ResponseBody
    @DeptPermValidate(id = "userId", deptId = "deptId")
    public JSONObject resetPassword(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        userService.resetPassword(reqBean.getInfo("userId"));
        return Response.responseSuccess();
    }

    @RequestMapping(value = "/tree")
    @ResponseBody
    public JSONObject userTree(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        String deptId = reqBean.getInfo("deptId");
        String userId = reqBean.getUserId();

        JSONArray jsonArray = new JSONArray();
        List<String> deptIds = new ArrayList<String>();
        for (IDepartment department : permissionService.getAuthedDepartments(userId, reqBean.getMenuId(), deptId)) {
            deptIds.add(department.getDeptId());

            JSONObject json = new JSONObject();
            json.put("id", "dept-" + department.getDeptId());
            json.put("pId", "dept-" + department.getParentDeptId());
            json.put("name", department.getDeptName());
            json.put("type", "dept");
            json.put("deptid", department.getDeptId());
            json.put("posid", "");
            jsonArray.add(json);
        }
        List<IUser> list = userService.queryUserOfDept(deptIds);
        for (IUser user : list) {
            JSONObject json = new JSONObject();
            json.put("id", user.getId());
            json.put("pId", "dept-" + user.getDeptId());
            json.put("name", user.getName());
            json.put("type", "user");
            json.put("deptid", user.getDeptId());
            json.put("posid", "");
            jsonArray.add(json);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("org", jsonArray);
        jsonObject.put("pos", new JSONArray());
        return Response.response(jsonObject);
    }

}
